#include "Sprite.h"

 
Sprite::Sprite(LPD3DXSPRITE SpriteHandler, Texture* Texture, float TimeAnimation, int Index)
	:texture(Texture)
{
	_SpriteHandler = SpriteHandler;
	_Index = 0;//Index;
	_TempIndex = Index;
	_frameBegin = _Index;
	_frameEnd = texture->_Count;
	_TimeAni = TimeAnimation;
	_TimeLocal = 0.0f;
}

Sprite::~Sprite()
{
	if (texture)
		texture->~Texture();
}

void Sprite::Render(float X, float Y, int vpX, int vpY)
{
	RECT srect;

	srect.left = (_Index % texture->_Cols) * texture->_Width;
	srect.top = (_Index / texture->_Cols) * texture->_Height;
	srect.right = srect.left + texture->_Width;
	srect.bottom = srect.top + texture->_Height;

	D3DXVECTOR3 position((float)X, (float)Y, 0);
	position.x = X + (float)texture->getWidth()/2;
	position.y = Y - (float)texture->getHeight()/2;

	D3DXMATRIX mt;
	D3DXMatrixIdentity(&mt);
	mt._22 = -1.0f;
	mt._41 = -vpX;
	mt._42 = vpY;

	D3DXVECTOR4 vp_pos;
	D3DXVec3Transform(&vp_pos,&position,&mt);

	D3DXVECTOR3 p(vp_pos.x, vp_pos.y,0);
	D3DXVECTOR3 center((float)texture->_Width/2,(float)texture->_Height/2,0);
	
	//D3DXVECTOR3 center(0,0,0);


	_SpriteHandler->Draw(
		texture->Get_Texture(),
		&srect,
		&center,
		&p,
		D3DCOLOR_XRGB(255, 255, 255));
}


void Sprite::Next()
{
	_Index ++;

	if (_Index < _frameBegin)
		_Index = _frameBegin;
	if (_Index > _frameEnd - 1)
		_Index = _frameBegin;	
}

void Sprite::Reset()
{
	_Index = _frameBegin;
	_TimeLocal = 0.0f;
}

void Sprite::ResetLeft()
{
	_Index = texture->_Count - 1;
	_TimeLocal = 0.0f;
}

void Sprite::Update(float DelTime)
{
	_TimeLocal += DelTime;
	if (_TimeLocal >= _TimeAni)
	{
		_TimeLocal = 0.0f;
		this->Next();
	}

}